package com.mobile.view.controller;

import com.mobile.view.util.FileUtil;
import com.mobile.view.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 扫描本地视频
 *
 * @author lr
 */
@Slf4j
@Controller
@RequestMapping("/view")
public class ViewController {
    public static String host = "http://127.0.0.1/";

    @Value("${web.upload.path}")
    private String uploadPath;

    @PostConstruct
    public void init() {
        File file = new File(uploadPath);
        if (!file.exists()) {
            log.error("扫描的视频路径不存在：{}", uploadPath);
            System.exit(0);
        } else if (!file.isDirectory()) {
            log.error("扫描的路径不是文件夹：{}", uploadPath);
            System.exit(0);
        }
    }

    private static List<String> delete = new LinkedList<>();

    @GetMapping("/del")
    @ResponseBody
    public String del(String filename, String delAll) throws Exception {
        filename = StringUtils.substringAfter(filename, "files/");
        int index = Integer.parseInt(StringUtils.substringBefore(filename, "/"));
        String[] pathFile = uploadPath.split(",");
        String fileDel = pathFile[index] + StringUtils.substringAfter(filename, "/");
        File file = new File(fileDel);

        if (file.exists() && file.isFile()) {
            if (file.length() > 1024 * 1024 * 50) {
                delete.add(fileDel);
                return "del 成功";
            }

            List<String> alls = new LinkedList<>();
            List<String> videos = new LinkedList<>();
            List<String> images = new LinkedList<>();
            getVideoAndImages(videos, images, null, alls);
            for (String all : alls) {
                File fileOthers = new File(all);
                if (fileOthers.exists() && fileOthers.isFile()) {
                    if (FileUtil.isSameFile(fileDel, all)) {
                        delete.add(all);
                    }
                }
            }
            //删除所有相关文件
            delAlls(delAll, file);
            return "del 成功";
        }
        return filename + "fail";
    }

    private void delAlls(String delAll, File file) {
        for (String del : delete) {
            //删除其他重复文件
            if (!delAll.equals("all")) {
                if (del.equals(file.getAbsolutePath())) {
                    continue;
                }
            }
            File delFile = new File(del);
            if (delFile.exists() && delFile.isFile()) {
                log.info("删除文件：" + delFile.getAbsolutePath());
                delFile.delete();
            }
        }

    }


    static List<String> videos = new LinkedList<>();
    static List<String> images = new LinkedList<>();
    static List<String> alls = new LinkedList<>();

    @GetMapping("/video")
    public String video(@RequestParam(value = "username", defaultValue = "all", required = false) String keyWord, @RequestParam(required = false) String videoB, ModelMap modelMap) throws Exception {

        for (String del : delete) {
            File delFile = new File(del);
            if (delFile.exists() && delFile.isFile()) {
                boolean deled = delFile.delete();
                if (deled) {
                    log.info("删除文件：" + delFile.getAbsolutePath());
                }
            }
        }

        if ("all".equals(keyWord)) {
            keyWord = null;
            getVideoAndImages(videos, images, keyWord, alls);
        } else if (StringUtils.isNotBlank(keyWord)) {
            getVideoAndImages(videos, images, keyWord, alls);
        } else if (delete.size() > 1 || alls.size() < 1 || videos.size() < 1) {
            getVideoAndImages(videos, images, keyWord, alls);
        }
        //倒序 随机
        // Collections.reverse(videos);
        // Collections.reverse(images);
        RandomUtil.shuffle2(videos);
        RandomUtil.shuffle2(images);

        modelMap.put("videos", videos);
        modelMap.put("images", images);
        if ("videoB".equals(videoB)) {
            return "view/videoB";
        }
        return "view/video";
    }

    private void getVideoAndImages(List<String> videos, List<String> images, String username, List<String> alls) {
        videos.clear();
        images.clear();
        alls.clear();
        String[] pathFile = uploadPath.split(",");
        for (int i = 0; i < pathFile.length; i++) {
            //D盘下的file文件夹的目录
            File file = new File(pathFile[i]);
            List<String> oneFiles = new LinkedList<>();

            oneFiles.addAll(getAllVideo(file, i));
            alls.addAll(oneFiles.stream().filter(name -> !name.startsWith("files/")).collect(Collectors.toList()));
            oneFiles = oneFiles.stream().filter(name -> name.startsWith("files/")).collect(Collectors.toList());

            if (StringUtils.isNotBlank(username)) {
                oneFiles = oneFiles.stream().filter(name -> containsKeyWord(name, username)).collect(Collectors.toList());

            }

            log.info("文件个数：：：：：：：：" + oneFiles.size());

            String fileParentPath = file.getAbsolutePath();
            for (String name : oneFiles) {
                name = name.replace(fileParentPath, "");
                name = StringUtils.replaceAll(name, "\\\\", "/");
                name = host + name;

                if (FileUtil.judgeFileIsVideo(name)) {
                    videos.add(name);
                } else if (FileUtil.judgeFileIsImage(name)) {
                    images.add(name);
                }
            }

        }

    }

    private boolean containsKeyWord(String word, String keyWord) {
        return word.contains(keyWord) || StringUtils.containsIgnoreCase(word, keyWord);
    }

    private List<String> getAllVideo(File file, int i) {
        List<String> names = new LinkedList<>();

        if (file == null) {
            return names;
        }
        //File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();

        if (fileList == null) {
            file.delete();
            return names;
        }
        if (fileList.length < 1) {
            file.delete();
            return names;
        }
        //将该目录下的所有文件放置在一个File类型的数组中
        for (File f : fileList) {
            if (f.isDirectory()) {
                //是文件夹，继续递归，如果需要重命名文件夹，这里可以做处理
                //System.out.println("文件夹:" + f.getAbsolutePath() + "，继续递归！");
                File file2 = new File(f.getAbsolutePath());//File类型可以是文件也可以是文件夹
                names.addAll(getAllVideo(file2, i));
            } else {
                names.add("files/" + i + f.getAbsolutePath());
                names.add(f.getAbsolutePath());
            }
        }
        return names;
    }


}
